<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户编号" prop="personId">
        <el-select v-model="queryParams.personId" placeholder="请选择用户">
          <el-option
            v-for="item in personList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品编号" prop="commId">
        <el-select v-model="queryParams.commId" placeholder="请选择商品">
          <el-option
            v-for="item in commList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-goods"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fuw:car:buyComm']"
        >购买</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fuw:car:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fuw:car:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['fuw:car:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="uId" />
      <el-table-column label="用户编号" align="center" prop="personId" />
      <el-table-column label="商品编号" align="center" prop="commId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fuw:car:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改购物车对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-timeline>
          <el-collapse accordion style="padding-top: 30px;margin-bottom: 30px;">
            <el-timeline-item
              v-for="(item, index) in commParam"
              :timestamp="item.commId"
              color="#0bbd87"
              placement="top">
              <el-collapse-item :title="item.commName">
                <el-card>
                  <el-row>
                    <el-col :span="10">
                      <el-card :body-style="{ padding: '0px' }">
                        <img :src="item.commPicture" class="image">
                        <div style="padding: 14px;">
                          <span>{{item.commName}}</span>
                          <div class="bottom clearfix">
                            <time class="time">简介：{{item.commText}}</time>
                          </div>
                        </div>
                      </el-card>
                    </el-col>

                    <el-col :span="12" style="margin-left:30px;">
                      <el-card :body-style="{ padding: '0px' }">
                        <el-descriptions class="margin-top" :column="1" size="medium" border>
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="el-icon-goods"></i>
                              商品名称
                            </template>
                            {{item.commName}}
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="el-icon-document"></i>
                              简介
                            </template>
                            {{item.commText}}
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="el-icon-money"></i>
                              单价
                            </template>
                            {{item.commDanjia}} 元
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="el-icon-bank-card"></i>
                              折扣
                            </template>
                            {{item.commZhekou}} 折
                          </el-descriptions-item>
                        </el-descriptions>
                      </el-card>
                    </el-col>

                  </el-row>
                </el-card>
              </el-collapse-item>

              <div style="margin-top: 20px;">
                <el-input-number placeholder="0" v-model="order.numList[index]" @change="handleChange(item)" :min="1" :max="item.commKucun" label="描述文字"></el-input-number>
              </div>
            </el-timeline-item>

          </el-collapse>
          </el-timeline>

        <el-form-item label="商品数量" prop="allNum">
          <el-input v-model="order.allNum" readonly="readonly" placeholder="0">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="总金额" prop="allMoney">
          <el-input v-model="order.allMoney" readonly="readonly" placeholder="0">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, listPersonId, listCommId, getCar, delCar, addCar, updateCar, addOrder, exportCar } from "@/api/fuw/car";
import { listCarComm } from "@/api/fuw/comm";

export default {
  name: "Car",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购物车表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 下拉框的2个数组
      personList: [],
      commList: [],
      // 商品信息详情
      commParam: [],
      // 存放当前商品的内容
      commIdList: {
        personId: null,
        commId: null
      },
      // 订单数据
      order: {
        // 商品数量数组
        numList: [],
        // 购买数量
        allNum: 0,
        // 总金额
        allMoney: 0
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personId: null,
        commId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        personId: [
          { required: true, message: "用户编号不能为空", trigger: "blur" }
        ],
        commId: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 查询下拉框数据
    this.getListByTabId();
  },
  methods: {
    /** 动态修改价格 */
    /**
     * @item 商品信息
     */
    handleChange(item) {
      console.log(this.commParam);
      // 总数量的计算
      let numAll = 0;
      for(let i=0; i<this.order.numList.length; i++){
        if(this.order.numList[i] == null){
          numAll = numAll;
        }else{
          numAll = numAll + this.order.numList[i];
        }
      }
      this.order.allNum = numAll;
      // 总金额计算
      let moneyAll = 0;
      const danjia = this.commParam.map(x => {return x.commDanjia});
      const zhekou = this.commParam.map(x => {return x.commZhekou});
      for(let i=0; i<this.order.numList.length; i++){
        if(this.order.numList[i] == null){
          moneyAll = moneyAll;
        }else{
          moneyAll = moneyAll + this.order.numList[i] * (danjia[i] * (1-zhekou[i]*0.1));
        }
      }
      this.order.allMoney = moneyAll.toFixed(3);

    },
    /** 查询下拉框列表 */
    getListByTabId() {
      listPersonId().then(response => {
        this.personList = response.data;
        this.getList();
      });
      listCommId().then(response => {
        this.commList = response.data;
        this.getList();
      });
    },
    /** 查询购物车列表 */
    getList() {
      this.loading = true;
      listCar(this.queryParams).then(response => {
        this.carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uId: null,
        personId: null,
        commId: null
      };
      this.commParam = [];
      // 存放当前商品的内容
      this.commIdList = {
          personId: null,
          commId: null
      };
      this.order = {
          numList: [],
          allNum: 0,
          allMoney: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.uId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 定义一个数组
      let carJson = '';
      for(let i=0;i<this.commList.length;i++){
        carJson = carJson + this.commList[i].value + ",";
      }
      this.commIdList.commId = carJson
      // 获取当前购物车中的商品详细信息
      listCarComm(this.commIdList).then(response => {
        // 给商品详情赋值
        this.commParam = response.data;
        this.open = true;
        this.title = "购买商品";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const uId = row.uId || this.ids
      getCar(uId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改购物车";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.order)
          // 总金额，对应购物车内商品的数量
          // 在购买时：
          // 1、在order表新增对应的订单信息 参数：（总金额）
          // 2、在orders表新增对应的多对多信息 参数：（商品数量数组，商品信息数组（顺序查询），用户ID，orderId）
          // 3、在新增orders内的信息后，在购物车内删除对应的商品信息

          //定义一个数组
          let carString = '';
          for(let i=0;i<this.carList.length;i++){
            carString = carString + this.carList[i].commId + ",";
          }

          //定义一个数组
          let numString = '';
          for(let i=0;i<this.order.numList.length;i++){
            numString = numString + this.order.numList[i] + ",";
          }

          let formData = new FormData();
          formData.append("allMoney", this.order.allMoney) // 总金额
          formData.append("carString", carString) // 商品的ID序号
          formData.append("numString", numString) // 商品的数量

          addOrder(formData).then(response => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uIds = row.uId || this.ids;
      this.$confirm('是否确认删除购物车编号为"' + uIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCar(uIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有购物车数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCar(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>

<style>
.time {
  font-size: 13px;
  color: #999;
}
.time2 {
  font-size: 14px;
  color: #000000;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.el-descriptions-item__label{
  width: 100px !important;
}
</style>
